<template>
    <div :style="style">
        <template v-if="disabled">
            <el-image v-if="disabled" :src="videopng" style="display: contents; cursor: pointer;width:24px;height:24px"
                fit="fill" @click="handleShowPlayer">
            </el-image>
        </template>
        <template v-else>
            <input ref="uploadInput" type="file" @click.stop accept="video/*" :multiple="false"
                @change="onFileChanged($event)" style="display: none;" />
            <div v-if="showDiv === 'preview'" style="height: 100%; width: 100%;">
                <el-popover placement="bottom" trigger="hover" style="height: 100%; width: 100%;">
                    <div class="video-toolset">
                        <el-button type="success" :icon="Search" circle @click="handleShowPlayer"></el-button>
                        <el-button type="success" :icon="Delete" circle @click="handleRemove"></el-button>
                    </div>
                    <template #reference>
                        <div class="video-preview">
                            <el-image v-if="!disabled" :src="videopng" fit="fill"
                                style="cursor: pointer;width:100%;height:100%" @click="handleShowPlayer">
                            </el-image>
                        </div>
                    </template>
                </el-popover>
            </div>

            <div v-if="showDiv === 'plus'" class="video-plus" @click="handleClickPlus">
                <el-icon :size="20">
                    <Plus />
                </el-icon>
            </div>
            <div v-if="showDiv === 'progress'" class="video-progress">
                <el-progress :percentage="percentage" :text-inside="false" type="circle" :status="processStatus">
                    <template #default="{ percentage }">
                        <span class="percentage-value">{{ percentage }}%</span>
                        <span class="percentage-label">{{ processTips }}</span>
                    </template>
                </el-progress>
            </div>
        </template>
    </div>
    <el-dialog v-model="dialogVisible" append-to-body width="50%" destroy-on-close @before-close="() => {
        dialogVisible = false
    }">
        <div style="z-index: 1000;display: flex;align-items: center;justify-content: center;">
            <div class="myplayer"></div>
            <!-- <videoPlay ref="video" :width="width" :height="height" :title="title" :src="videoSrc" :poster="poster"
                @play="onPlay" @pause="onPause" @timeupdate="onTimeupdate" @canplay="onCanplay" /> -->
        </div>
    </el-dialog>
</template>
<script setup lang="ts">
import "vue3-video-play/dist/style.css";
import { videoPlay } from "vue3-video-play";
import { defineProps, defineModel, Ref, ref, watch, onMounted } from 'vue';
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import elHelper from "@/common/elHelper";
import { ServerConfig, Sysinfo } from "@/common/config";
import comFunc from "@/common/comFunc";
import { deleteFile, uploadVideo } from "@/api/file";
import videopng from '@/assets/images/video.png'
import { t } from "@/common/locale";
import { useUsers } from "@/stores";
import { Oss } from "@/common/aliyunOssHelper";

const props = defineProps({
    width: {
        type: String,
        default: '100%'
    },
    height: {
        type: String,
        default: '400px'
    },
    style: {
        type: Object,
        default: {
            width: '160px',
            height: '160px'
        }
    },
    title: {
        type: String,
        default: ''
    },
    poster: {
        type: String,
        default: ''
    },
    autoUpload: {
        type: Boolean,
        default: true
    },
    disabled: {
        type: Boolean,
        default: false
    }
})
const emit = defineEmits(['onUploaded'])
const userStore = useUsers()

const dialogVisible = ref(false)
const model = defineModel({ type: String })
const videoSrc = ref('')
const showDiv: Ref<'' | 'plus' | 'progress' | 'preview'> = ref('plus')
const uploadInput = ref()
const percentage = ref(0)
const video = ref()
const processTips = ref('')
const processStatus = ref<"" | "success" | "warning" | "exception">('')
let file: any = null

watch(() => model.value, (val) => {
    setVideoSrc(comFunc.nvl(val))
    setShowState()
})

const onFileChanged = async (e: any) => { // 点击上传
    const files = e.target.files
    if (files?.length && files?.length > 0) {
        showDiv.value = 'preview'
        file = files[0]
        const maxsize = Sysinfo.VideoUploadMaxSize
        if (file.size > maxsize * 1024 * 1024) { // 限制上传图片文件大小
            elHelper.showErrorMsg(`上传大小不能超过 ${maxsize}M!`)
        } else {
            var reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = function (result) {
            }
            if (props.autoUpload) {
                const re = await upload()
                if (!re.isSuccess) {
                    elHelper.showErrorMsg(comFunc.nvl(re.msg))
                }
            }
        }
    }
}
const handleShowPlayer = () => {
    if (onCCH5PlayerLoaded()) {
        dialogVisible.value = true
    }
}
const handleRemove = async () => {
    if (model.value && model.value.startsWith('/')) {
        await deleteFile(comFunc.nvl(model.value))
    }
    videoSrc.value = ''
    showDiv.value = 'plus'
    file = null
    uploadInput.value.value = ''
}
const upload = async (): Promise<{
    isSuccess: boolean,
    msg?: string,
    path?: string,
    remotePath?: string,
    videoId?: string
}> => {
    if (file) {
        console.log(file)
        percentage.value = 0
        showDiv.value = 'progress'
        processTips.value = t('处理中...')
        processStatus.value = ''
        const re = await uploadVideo(file, file.name, (per) => {
            percentage.value = per
        })
        // const re = await Oss.upload(file, (per) => {
        //     percentage.value = per
        // })

        if (re.isSuccess) {
            //model.value = re.path
            model.value = re.videoId
            processTips.value = t('完成')
            processStatus.value = 'success'
            showDiv.value = 'preview'
            setShowState()
            emit('onUploaded', {
                path: re.path,
                remotePath: re.remotePath,
                videoId: re.videoId
            })
            return {
                isSuccess: true,
                path: comFunc.nvl(re.path),
                remotePath: comFunc.nvl(re.remotePath),
                videoId: re.videoId
            }
        } else {
            processTips.value = t('失败')
            processStatus.value = 'exception'
            setTimeout(() => {
                handleRemove()
            }, 1000);
            return {
                isSuccess: false,
                msg: '上传失败'
            }
        }
    } else {
        return {
            isSuccess: true,
            path: model.value,
            remotePath: ServerConfig.REMOTE_FILE_BASE + model.value,
            videoId: model.value
        }
    }
}
const handleClickPlus = () => {
    uploadInput.value.click()
}
const onPlay = (ev) => {

}
const onPause = (ev) => {

}

const onTimeupdate = (ev) => {

}
const onCanplay = (ev) => {

}
const setVideoSrc = (v: string | undefined) => {
    if (!v) {
        videoSrc.value = ''
        return
    }
    if (v.startsWith('/')) {
        videoSrc.value = ServerConfig.REMOTE_FILE_BASE + v
    } else {
        videoSrc.value = v
    }
}
const setShowState = () => {
    if (props.disabled) {
        showDiv.value = 'preview'
    } else {
        if (comFunc.nvl(model.value) !== '') {
            showDiv.value = 'preview'
        } else {
            showDiv.value = 'plus'
        }
    }
}
const onCCH5PlayerLoaded = (): boolean => {
    //使用播放器提供的window下的createCCH5Player方法创建播放器
    const obj: any = window
    let elems = document.getElementsByClassName('myplayer');
    if (!userStore.siteId || userStore.siteId) {
        elHelper.showWarningMsg('观看权限不足')
        return false
    } else {
        var playerNew = obj.createCCH5Player({
            'vid': model.value,
            'siteid': userStore.siteId,
            'mediatype': 1,
            'autoStart': 'true',
            'width': '100%',
            'height': '100%',
            'isShare': 'false',
            'banDrag': 'false',
            'parentNode': elems[0]
        })
        return true
    }
}
onMounted(() => {
    setVideoSrc(model.value)
    setShowState()
})

</script>
<style lang="scss" scoped>
@mixin video-container {
    border: 1px solid var(--border-color);
    border-radius: 5px;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.video-plus {
    @include video-container()
}

.video-preview {
    @include video-container()
}

.video-toolset {
    display: flex;
    justify-content: center;
    // background-color: rgba(128, 128, 128, 0.5);
    border-radius: 5px;
}

.video-progress {
    padding: 2px 0 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
}

.percentage-value {
    width: 100%;
    align-content: center;
}

.percentage-label {
    width: 100%;
    align-content: center;
}
</style>